package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass =CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {

        //新增检查组，操作t_checkgroup表
        checkGroupDao.add(checkGroup);

        //新增关系表
        Integer checkgroupId = checkGroup.getId();
        this.setCheckGroupAndCheckItem(checkgroupId,checkitemIds);

    }


    //分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> page=checkGroupDao.findBycondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupIds(Integer id) {
        return checkGroupDao.findCheckItemIdsByCheckGroupIds(id);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //修改检查组基本信息
        checkGroupDao.edit(checkGroup);

        //删除检查项关联数据
        checkGroupDao.deleteAssocication(checkGroup.getId());
        //添加检查组新的关联关系
        this.setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);

    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }


    public void setCheckGroupAndCheckItem(Integer checkgroupId,Integer[] checkitemIds){
        if (checkitemIds!=null &&checkitemIds.length>0){
            for (Integer checkitemId : checkitemIds) {
                Map<String,Integer> map= new HashMap<String, Integer>();
                map.put("checkitemId",checkitemId);
                map.put("checkgroupId",checkgroupId);
                checkGroupDao.setCheckGroupAndCheckItem(map);
            }
        }
    }
}
